import logging

from django.utils.deprecation import MiddlewareMixin

from libs.useragent_parser import ua_parser

visitor_logger = logging.getLogger("visitor")


class GuestOperation(MiddlewareMixin):
    """来访者操作中间件"""

    def process_request(self, request):
        ip = request.META["REMOTE_ADDR"]

        visitor_logger.info(f'{ip} 访问')  # 访问记录
        user_agent = request.META["HTTP_USER_AGENT"]
        user_agent_parse = ua_parser(user_agent)
        user_agent_parse["ip"] = ip
        user_agent_parse["user_agent"] = user_agent  # 将解析内容封入请求

        setattr(request, "USER_AGENT_PARSE", user_agent_parse)


